package com.bw.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * @author Monte
 * @author 644527030@qq.com
 * @author 知识改变命运，代码改变世界！
 * @date 2024年07月18日    10:45
 * @PackageName:com.bw.utils
 * @ClassName: AesUtil
 * @Description HomeController
 */

public class AesUtil {
    private static final String ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     * @param data
     * @param secretKey
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String secretKey) throws Exception {
        byte[] keyBytes = secretKey.getBytes("UTF-8");
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        byte[] encryptedBytes = cipher.doFinal(data.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 解密
     * @param encryptedData
     * @param secretKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptedData, String secretKey) throws Exception {
        byte[] keyBytes = secretKey.getBytes("UTF-8");
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

        byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);

        return new String(decryptedBytes, "UTF-8");
    }
}
